package cn.lastcc.pwdmanage.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StreamCorruptedException;

import cn.lastcc.pwdmanage.R;
import cn.lastcc.pwdmanage.core.CustomApp;
import cn.lastcc.pwdmanage.core.MD5;
import cn.lastcc.pwdmanage.core.SerialUtil;
import cn.lastcc.pwdmanage.entity.IConstant;
import cn.lastcc.pwdmanage.entity.Info;

/**
 * 登陆窗口
 *
 * @author Added by baidongyang 2013-6-22
 * @version 15.5.23.1
 *
 */
public class LogonActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {

    private SerialUtil mSerialUtil = null;

    // 声明控件
    private EditText txtPwd = null;
    private CheckBox chkShowPwd = null;
    private Button btnLogon = null;

    // 密码文件版本检查结果：true 升级；false 无需升级
    private static boolean checkResult = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setTitle("登录");
        mSerialUtil = SerialUtil.getInstance(this);
        requestStoragePermissions(this);
    }

    private void init() {
        // 如果第一次使用本程序，则直接进入主界面
        Info info = null;
        try {
            info = mSerialUtil.getInfo();
            if (null == info) {
                this.startMainActivity(null);
                return;
            }
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
            this.startMainActivity(null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            this.startMainActivity(null);
        } catch (IOException e) {
            e.printStackTrace();
            this.startMainActivity(null);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            this.startMainActivity(null);
        }
        setContentView(R.layout.activity_logon);
        // 通过控件 ID 获得控件对象
        this.txtPwd = (EditText) this.findViewById(R.id.txtPwd_lon);
        this.chkShowPwd = (CheckBox) this.findViewById(R.id.chkShowPwd_lon);
        this.btnLogon = (Button) this.findViewById(R.id.btnLogon_lon);

        // 校验文件版本
        this.checkInfoVersion(info);

        // 给显示密码复选框添加监听事件
        this.chkShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 如果选中则显示密码，否则隐藏密码
                if (isChecked) {
                    txtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    txtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        // 给登陆按钮增加单击事件
        this.btnLogon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String inputPwd = txtPwd.getText().toString();
                // 校验密码不能为空
                if ("".equals(inputPwd)) {
                    Toast.makeText(v.getContext(), R.string.msg_logonActivity_pwdPrompt, Toast.LENGTH_LONG).show();
                    return;
                } else {
                    Info info = null;
                    try {
                        info = mSerialUtil.getInfo();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(v.getContext(), R.string.msg_logonActivity_logonException, Toast.LENGTH_LONG).show();
                        return;
                    }
                    MD5 m = new MD5();
                    if (!m.cell32(inputPwd).equals(info.getUserPassword())) {
                        new AlertDialog.Builder(LogonActivity.this)
                                .setTitle(R.string.str_globe_dialogTitle_prompt)
                                .setMessage(R.string.msg_logonActivity_logonFailed)
                                .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .create().show();
                        return;
                    }
                    if (checkResult) {
                        Toast.makeText(LogonActivity.this.getApplicationContext(), "正在升级密码库，请稍候", Toast.LENGTH_SHORT).show();
                        // 更新密码文件
                        updateInfoVersion(inputPwd, info);
                        Toast.makeText(LogonActivity.this.getApplicationContext(), "恭喜，密码库升级完毕", Toast.LENGTH_SHORT).show();
                    }
                    startMainActivity(inputPwd);
                }
            }
        });
    }

    /**
     * 启动 MainActivity 并关闭当前 Activity
     *
     * @author Added by baidongyang 2013-6-23
     */
    private void startMainActivity(String logonPwd) {
        Intent intent = new Intent();
        intent.setClass(LogonActivity.this, MainActivity.class);
        intent.putExtra(IConstant.LOGIN_PARAM_PWD_LBL, logonPwd);
        startActivity(intent);
        // 关闭当前窗口
        LogonActivity.this.finish();
    }

    /**
     * 关闭此 Activity 则退出整个应用
     */
    @Override
    public void finish() {
        super.finish();
        System.exit(0);
    }

    /**
     * 检查密码文件版本
     * @param info 不能为 null
     * @author Added by baidongyang 2015-05-23
     */
    private void checkInfoVersion (Info info) {
    	int fversion = Integer.parseInt(info.getFileVersion());

    	this.btnLogon.setEnabled(false);
    	if (fversion < IConstant.INFO_CUR_VERSION_DIGIT) { // 升级文件
   		 new AlertDialog.Builder(LogonActivity.this)
         .setTitle(R.string.str_globe_dialogTitle_prompt)
         .setMessage(R.string.str_mainActivity_chkInfoVerL)
         .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
            	 checkResult = true;
             }
         })
         .setNegativeButton(R.string.str_globe_Cancel, new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
            	// 退出应用程序
            	 LogonActivity.this.finish();
                 System.exit(0);
             }
         })
         .setCancelable(false) // 禁止按下返回键关闭对话框
         .create().show();
    	} else if (fversion > IConstant.INFO_CUR_VERSION_DIGIT) { // 文件版本较高，禁止运行
    		 new AlertDialog.Builder(LogonActivity.this)
             .setTitle(R.string.str_globe_dialogTitle_prompt)
             .setMessage(R.string.str_mainActivity_chkInfoVerH)
             .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                	// 退出应用程序
                	 LogonActivity.this.finish();
                     System.exit(0);
                 }
             })
             .setCancelable(false) // 禁止按下返回键关闭对话框
             .create().show();
    	}
    	this.btnLogon.setEnabled(true);
    	checkResult = false;
    }

    /**
     * 升级密码文件<br/>
     * <span style="color: #FF0000;">每次修改密码文件的存储规则时都要根据新的存储规则和旧的存储规则修改这个方法！</span>
     * @param logonPwd
     * @param info
     * @author Added by baidongyang 2015-05-23
     */
    private void updateInfoVersion (String logonPwd, Info info) {
    	CustomApp customApp = (CustomApp) LogonActivity.this.getApplication();
        int fversion = Integer.parseInt(info.getFileVersion());
    	if (fversion < IConstant.INFO_VERSION_3_DIGIT) {
            new AlertDialog.Builder(LogonActivity.this)
                    .setTitle(R.string.str_globe_dialogTitle_prompt)
                    .setMessage(R.string.msg_logonActivity_noSupportUpgrade)
                    .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 退出应用程序
                            LogonActivity.this.finish();
                            System.exit(0);
                        }
                    })
                    .setCancelable(false) // 禁止按下返回键关闭对话框
                    .create().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        boolean isSuccess = true;
        if (grantResults.length == 0) {
            isSuccess = false;
        }
        for (int ret : grantResults) {
            if (PackageManager.PERMISSION_GRANTED != ret) {
                isSuccess = false;
                break;
            }
        }
        if (!isSuccess) {
            new AlertDialog.Builder(LogonActivity.this)
                    .setTitle(R.string.str_globe_dialogTitle_error)
                    .setMessage(R.string.str_mainActivity_reqPermissionFail)
                    .setPositiveButton(R.string.str_globe_OK, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 退出应用程序
                            LogonActivity.this.finish();
                            System.exit(0);
                        }
                    })
                    .setCancelable(false) // 禁止按下返回键关闭对话框
                    .create().show();
            return ;
        }
        init();
    }

    private static void requestStoragePermissions(LogonActivity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            activity.init();
            return ;
        }
        try {
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(activity
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(activity
                        , new String[]{Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE}
                        , 1);
            } else {
                activity.init();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
